package mail.util;

import java.io.IOException;
import java.net.http.HttpHeaders;
import java.net.http.HttpResponse;
import java.util.Optional;

/**
 * @author: Hanjiafeng
 * @date: Created in 16:11 2019/1/25
 * @desc: 从HttpResponse中获取指定数据
 */
public class HttpResponseUtil {

    /**
     * 获取重定向url
     *
     * @param response 响应头
     * @return 重定向url
     */
    public static String getLocation(HttpResponse response) {
        return getSpecifiedValue(response, "Location");
    }

    /**
     * 获取Content-Type中的编码方式,如果没有其中没有编码方式,默认返回utf8
     *
     * @param response 响应头
     * @return charset
     */
    public static String getCharset(HttpResponse response) {
        String contentType = getSpecifiedValue(response, "Content-Type");
        contentType = contentType.toLowerCase();
        String charset = RegexSearcher.matchFirst(contentType, "(?<=charset=)((?!\\s)(?!,)(?!\\;).)*");
        return charset.isBlank() ? "utf8" : charset;
    }

    /**
     * 获取指定key对应的value
     *
     * @param response 响应头
     * @param key      key
     * @return value
     */
    private static String getSpecifiedValue(HttpResponse response, String key) {
        HttpHeaders httpHeaders = response.headers();
        Optional<String> valueOp = httpHeaders.firstValue(key);
        if (valueOp.isPresent()) {
            return valueOp.get();
        } else {
            throw new NullPointerException(key + "不存在");
        }
    }

    public static String getBody(HttpResponse<byte[]> response) throws IOException {
        String charset = getCharset(response);
        return new String(UnZipper.unGzipByBytes(response.body()), charset);
    }
}
